package com.flyxiaozhu.erp.service.resolvers;

import com.flyxiaozhu.erp.core.repositories.AppRepository;
import com.flyxiaozhu.erp.service.annotations.ContextApp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

public class ContextAppResolver implements HandlerMethodArgumentResolver {

    @Autowired
    AppRepository appRepository;

    @Value("${app.sign.field-name.appid}")
    private String fieldNameAppId;

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.hasParameterAnnotation(ContextApp.class);
    }

    @Nullable
    @Override
    public Object resolveArgument(MethodParameter methodParameter, @Nullable ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, @Nullable WebDataBinderFactory webDataBinderFactory) throws Exception {
        String appId = nativeWebRequest.getParameter(fieldNameAppId);
        if (appId == null) {
            return null;
        }

        return appRepository.findById(Long.valueOf(appId)).orElse(null);
    }
}
